<template>
    <div>
        <div ref="main" style="width: 840px; height: 450px;"></div>
    </div>
</template>

<script lang='ts' setup>
import * as echarts from 'echarts'
import { ref, onMounted, watchEffect } from 'vue'
import api from '@/api'

//创建月份数组
const monthsList = ref<Array<string>>([])
//创建居民数量数组
const peopleData = ref<Array<string>>([])
//创建签约数据数组
const contractData = ref<Array<string>>([])
//创建服务数据数组
const serviceData = ref<Array<string>>([])
//获取echarts图表数据
const getPeopleContractData = async () => {
    const result = await api.workbench.getPeopleContractApi({ months: 12 })
    // console.log(result.data.data);
    result.data.data.resident.forEach((item: any) => {
        monthsList.value.push(item[0])
        peopleData.value.push(item[1])
    });

    result.data.data.service.forEach((item: any) => {
        contractData.value.push(item[1])
    });

    result.data.data.sign.forEach((item: any) => {
        serviceData.value.push(item[1])
    });

    // console.log(serviceData.value);
}

getPeopleContractData()
const main = ref<HTMLElement>();
const myChart = ref<any>();
function initBarEcharts() {
    myChart.value = echarts.init(main.value!);
    myChart.value.setOption({
        title: {
            text: '数据概况'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['居民数量', '签约量', '服务量']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: monthsList.value
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '居民数量',
                type: 'line',
                data: peopleData.value
            },
            {
                name: '签约量',
                type: 'line',
                data: contractData.value
            },
            {
                name: '服务量',
                type: 'line',
                data: serviceData.value
            }
        ]
    })
}

onMounted(() => {
    initBarEcharts();
});
//watchEffect钩子函数来监听monthsList.value的变化。当monthsList.value发生变化时，会重新设置图表的选项，更新x轴的数据
watchEffect(() => {
    myChart.value?.setOption({
        xAxis: {
            data: monthsList.value,
        },
        series: [
            {
                data: peopleData.value
            },
            {
                data: contractData.value
            },
            {
                data: serviceData.value
            },
        ]
    });
});
</script>

<style lang='scss' scoped></style>